import { defineStore } from 'pinia'
import { workOrdersApi } from '@/api'

export const useWorkOrderStore = defineStore('workOrders', {
  state: () => ({
    workOrders: [],
    selectedWorkOrder: null,
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0
    },
    filters: {
      status: '',
      search: ''
    },
    loading: false,
    error: null
  }),

  getters: {
    filteredWorkOrders(state) {
      return state.workOrders.filter(order => {
        const matchesStatus = !state.filters.status || 
          order.status === state.filters.status
        const matchesSearch = !state.filters.search || 
          order.title.toLowerCase().includes(state.filters.search.toLowerCase())
        return matchesStatus && matchesSearch
      })
    }
  },

  actions: {
    async fetchWorkOrders() {
      this.loading = true
      try {
        const response = await workOrdersApi.getWorkOrders(
          this.pagination.page,
          this.pagination.pageSize,
          this.filters.status,
          this.filters.search
        )
        this.workOrders = response.data
        this.pagination.total = response.total
      } catch (error) {
        this.error = error
      } finally {
        this.loading = false
      }
    },

    async createWorkOrder(workOrderData) {
      try {
        const response = await workOrderService.createWorkOrder(workOrderData)
        this.workOrders.unshift(response)
        return response
      } catch (error) {
        throw error
      }
    },

    async updateWorkOrder(id, updateData) {
      try {
        const response = await workOrderService.updateWorkOrder(id, updateData)
        const index = this.workOrders.findIndex(o => o.id === id)
        if (index !== -1) {
          this.workOrders.splice(index, 1, response)
        }
        return response
      } catch (error) {
        throw error
      }
    },

    async deleteWorkOrder(id) {
      try {
        await workOrderService.deleteWorkOrder(id)
        this.workOrders = this.workOrders.filter(o => o.id !== id)
      } catch (error) {
        throw error
      }
    },

    setFilters(filters) {
      this.filters = { ...this.filters, ...filters }
    },

    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination }
    },

    selectWorkOrder(workOrder) {
      this.selectedWorkOrder = workOrder
    },

    clearSelectedWorkOrder() {
      this.selectedWorkOrder = null
    }
  }
})